package com.king.framework.security.service;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.king.common.constant.CacheConstants;
import com.king.common.constant.Constants;
import com.king.common.exception.user.UserPasswordNotMatchException;
import com.king.common.exception.user.UserPasswordRetryLimitExceedException;
import com.king.common.utils.MessageUtils;
import com.king.common.utils.SecurityUtils;
import com.king.common.utils.redis.RedisUtil;
import com.king.framework.manager.AsyncManager;
import com.king.framework.manager.factory.AsyncFactory;
import com.king.framework.security.context.AuthenticationContextHolder;
import com.king.modules.system.domain.SysUserEntity;

/**
 * 登录密码方法
 * 
 * @author king
 */
@Component
public class SysPasswordService {
	@Autowired
	private RedisUtil redisCache;

	@Value(value = "${user.password.maxRetryCount}")
	private int maxRetryCount;

	@Value(value = "${user.password.lockTime}")
	private int lockTime;

	/**
	 * 登录账户密码错误次数缓存键名
	 * 
	 * @param username
	 *            用户名
	 * @return 缓存键key
	 */
	private String getCacheKey(String username) {
		return CacheConstants.PWD_ERR_CNT_KEY + username;
	}

	public void validate(SysUserEntity user) {
		Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
		String username = usernamePasswordAuthenticationToken.getName();
		String password = usernamePasswordAuthenticationToken.getCredentials().toString();

		Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

		if (retryCount == null) {
			retryCount = 0;
		}

		if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
			AsyncManager.me().execute(AsyncFactory.recordLoginLog(username, Constants.LOGIN_FAIL,
					MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
			throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
		}

		if (!matches(user, password)) {
			retryCount = retryCount + 1;
			AsyncManager.me().execute(AsyncFactory.recordLoginLog(username, Constants.LOGIN_FAIL,
					MessageUtils.message("user.password.retry.limit.count", retryCount)));
			redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
			throw new UserPasswordNotMatchException();
		} else {
			clearLoginRecordCache(username);
		}
	}

	public boolean matches(SysUserEntity user, String rawPassword) {
//		if(System.currentTimeMillis()>0){
//			return true;//TODO
//		}
		return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
	}

	public void clearLoginRecordCache(String loginName) {
		if (redisCache.hasKey(getCacheKey(loginName))) {
			redisCache.deleteObject(getCacheKey(loginName));
		}
	}
}
